<?php

namespace app\api\controller;

use ba\Captcha;
use ba\Random;
use think\facade\Db;
use app\common\controller\Api;
use app\common\library\Auth;
use app\api\validate\User as UserValidate;
use app\common\controller\Frontend;
use think\facade\Validate;

class User extends Frontend
{
    protected array $noNeedLogin = ['checkIn', 'verify', 'checkMobile'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 检查手机号是否已存在
     */
    public function checkMobile(): void
    {
        $mobile = $this->request->post('mobile');

        if (!$mobile) {
            $this->error('手机号不能为空');
        }

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('手机号格式不正确');
        }

        // 检查手机号是否已存在
        $existUser = Db::name('user')->where('mobile', $mobile)->find();

        $this->success('', [
            'exists' => $existUser ? true : false
        ]);
    }

    /**
     * 会员登录和注册
     */
    public function checkIn(): void
    {
        $params = $this->request->post(['nickname', 'mobile', 'registerType']);

        // 简化验证规则
        $validate = Validate::rule([
            // 'nickname' => 'require|length:2,15',
            'mobile'   => 'require|mobile',
        ]);

        if (!$validate->check($params)) {
            $this->error('参数验证失败');
        }

        $auth = Auth::instance();

        // 检查是否为注册
        if (isset($params['registerType']) && $params['registerType'] === 'register') {
            // 检查手机号是否已存在
            $existUser = Db::name('user')->where('mobile', $params['mobile'])->find();
            if ($existUser) {
                $this->error('手机号已存在');
            }

            // 用户名设置为手机号
            $username = $params['mobile'];

            // 默认密码为手机号后三位
            $defaultPassword = substr($params['mobile'], -3);

            // 注册逻辑 - 使用手机号作为用户名
            if (!$auth->register($username, $defaultPassword, $params['mobile'], '', 1, ['nickname' => $params['nickname']])) {
                $this->error($auth->getError());
            }
        } else {
            // 登录逻辑 - 仅使用手机号
            $user = Db::name('user')->where('mobile', $params['mobile'])->find();
            if (!$user) {
                $this->error('手机号不存在');
            }

            // 使用手机号后三位作为密码验证
            $defaultPassword = substr($params['mobile'], -3);
            if (!$auth->login($params['mobile'], $defaultPassword, true)) {
                $this->error($auth->getError());
            }
        }

        $this->success('', [
            'userInfo'     => $auth->getUserInfo(),
            'token'        => $auth->getToken(),
            'refreshToken' => $auth->getRefreshToken(),
        ]);
    }

    /**
     * 验证用户登录状态（用于自动登录）
     */
    public function verify(): void
    {
        $token = $this->request->header('token') ?: $this->request->param('token');

        if (!$token) {
            $this->error('Token不能为空', [], 401);
        }

        $auth = Auth::instance();
        if ($auth->init($token)) {
            $this->success('', [
                'userInfo' => $auth->getUserInfo(),
                'token'    => $token,
            ]);
        } else {
            $this->error('Token验证失败', [], 401);
        }
    }

    /**
     * 会员注销
     */
    public function logout(): void
    {
        $this->auth->logout();
        $this->success();
    }

    /**
     * 检查登录状态
     */
    public function checkLogin(): void
    {
        if ($this->auth->isLogin()) {
            $this->success('', [
                'userInfo' => $this->auth->getUserInfo(),
            ]);
        } else {
            $this->error(__('Please login first'), [], 401);
        }
    }
}
